package user

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/config"
	"iot-base/auth/db"
	types2 "iot-base/auth/types"
	"iot-base/common/jwt"
	"strconv"
	"time"
)

// Login 登录.
func Login(c *gin.Context) {
	resp := types2.NewResult(c)
	userLogic := logic2.NewUserLogic()
	var loginData LoginData
	err := c.ShouldBind(&loginData)
	if err != nil {
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	token, userInfo, err := userLogic.LoginToken(loginData.Username, loginData.Password)
	c.Set("uid", userInfo.ID)
	if err != nil {
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	// 查询用户拥有用的组
	groupModel := logic2.NewUserGroupLogic()
	groups, _ := groupModel.GetUserGroup(userInfo.ID)
	respGroup := make([]map[string]interface{}, 0, len(groups))
	for index := range groups {
		temp := map[string]interface{}{
			"id":         groups[index].ID,
			"group_name": groups[index].GroupName,
		}
		respGroup = append(respGroup, temp)
	}
	resp.Success(gin.H{"token": token, "user_type": userInfo.UserType, "groups": respGroup, "p_type": config.PType, "is_gate": config.IsGate})
	return
}

func SignOut(c *gin.Context) {
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	db.NewRedis().HDel(db.KeyUserLogin, strconv.FormatInt(uid, 10))
	resp.Success(gin.H{})
	return
}

// RefreshToken 刷新token.
func RefreshToken(c *gin.Context) {
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	redis := db.NewRedis()
	redisToken, _ := redis.HGet(db.KeyUserLogin, strconv.FormatInt(uid, 10))
	reToken, err := jwt.NewJWT().RefreshToken(redisToken, time.Now().Add(time.Hour*2).Unix())
	if err != nil {
		if err == jwt.TokenExpired {
			resp.ErrorCode(types2.TokenIsExpire, "授权已过期")
			return
		}
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	redis.HSet(db.KeyUserLogin, strconv.FormatInt(uid, 10), reToken)
	resp.Success(gin.H{"token": reToken})
}
